<template>
  <Chat :messageList="messageList" @closeWebSocket="closeWebSocket" style="height: 100vh;width: 100vw;"/>
</template>

<script setup>
import "../assets/index.css"
import {onMounted, toRaw, watch} from "vue";
import {useStore} from "@/stores"
import {get} from "@/net";
import Chat from "@/components/Chat.vue";

let socket
const store = useStore();
const messageList = store.messageList
let listV2
const {ipcRenderer} = require('electron');

// 判断当前浏览器是否支持webSocket

onMounted(
    () => {
      ipcRenderer.send("messageList", toRaw(store.messageList))
      getFriendList()
      getMessage()
      websocketConnect()
    }
)

watch(
    () => store.messageList.length,
    () => {
      if (store.messageList.length >= 100000) {
        store.messageList.splice(0, 100)
      }
    }
)

function getFriendList() {
  get(`/cat/message/getFriendList/${store.auth.user.id}`, (data) => {
    store.friendList.friendList = data.data
    if (localStorage.getItem(`friendList:${store.auth.user.id}`) == null) {
      for (let i = 0; i < store.friendList.friendList.length; i++) {
        let newArray = store.friendList.friendList[i].list.map(obj => obj.avatar);
        ipcRenderer.send("avatarList", newArray)
      }
    }
    localStorage.setItem(`friendList:${store.auth.user.id}`, '1')
  }, (data) => {

  })
}

function identifyGroupsOrUsers(message, data) {
  if (message.fromUserId[0] == 'G') {
    return {
      id: message.fromUserId,
      avatar: data.data.avatar,
      username: data.data.username,
      isGroup: true,
      level: 0,
      newMessage: '',
      newMessageName: ''
    }
  } else {
    return {
      id: message.fromUserId,
      avatar: data.data.avatar,
      username: data.data.username,
      isGroup: false,
      level: 0,
      newMessage: ''
    }
  }
}

function popUpsAndUpdates(one, message) {
  ++one.level
  if (message.type == 2) {
    one.newMessage = '图片'
  } else
    one.newMessage = message.message.replace(/<img[^>]*>/g, '图片')
  ipcRenderer.send('vue-message', {
    avatar: one.avatar,
    username: one.username,
    message: one.newMessage
  })
  one.newMessageName = message.messageUser
}

const websocketConnect = () => {
  if (window.WebSocket) {
    socket = new WebSocket("wss://www.ourcats.top/webSocket")
    // 相当于channel的read事件，ev 收到服务器回送的消息
    socket.onmessage = function (ev) {
      let message = JSON.parse(ev.data)
      if (message.type == 3) {
        let number = store.messageList.find(item => item.id == message.id);
        number.type = 3
        let one = store.userList.userList.find(one => one.id == number.fromUserId)
        if (number.messageUser !== undefined || number.messageUser != null){
          one.newMessage = `${number.messageUser}撤回一条消息`
          number.message = `${number.messageUser}撤回一条消息`
        }else {
          one.newMessage = `${number.username}撤回一条消息`
          number.message = `${number.username}撤回一条消息`
        }
        one.newMessageName = ''

        return
      }
      if (message.message !== undefined) {
        if (!store.userList.userList.some(one => one.id == message.fromUserId)) {
          let find = store.friendList.friendList.find(one => one.id == message.fromUserId);
          if (find == null) {
            get(`/cat/user/${message.fromUserId}`, (data) => {
              let user
              user = identifyGroupsOrUsers(message, data);
              store.userList.userList.push(user)
              let one = store.userList.userList.find(one => one.id == message.fromUserId)
              popUpsAndUpdates(one, message);
              store.userList.userList.sort((a, b) => b.level - a.level)
            })
          } else {
            store.userList.userList.push(find)
            let one = store.userList.userList.find(one => one.id == message.fromUserId)
            popUpsAndUpdates(one, message);
            store.userList.userList.sort((a, b) => b.level - a.level)
          }
        } else {
          let one = store.userList.userList.find(one => one.id == message.fromUserId)
          popUpsAndUpdates(one, message);
          store.userList.userList.sort((a, b) => b.level - a.level)
        }
        messageList.push(message)
        ++store.MessageNum
      }
      console.timeEnd()
    }
    // 相当于连接开启
    socket.onopen = function (ev) {
      console.log("连接开启了...")
      socket.send(
          JSON.stringify({
            // 连接成功将，用户ID传给服务端
            uid: store.auth.user.id
          })
      );
    }
    // 相当于连接关闭
    socket.onclose = function (ev) {
      console.log("连接关闭了...")
    }
  } else {
    alert("当前浏览器不支持webSocket")
  }
}

const closeWebSocket = () => {
  socket.close()
}

function offlineMessageProcessing(filteredArrayAs12, i) {
  let one = store.userList.userList.find(one => one.id == filteredArrayAs12[i].fromUserId)
  if (filteredArrayAs12[i].type == 3) {
    one.newMessage = filteredArrayAs12[i].message
  } else if (filteredArrayAs12[i].type == 2) {
    one.newMessage = '图片'
    ++one.level
  } else {
    one.newMessage = filteredArrayAs12[i].message.replace(/<img[^>]*>/g, '图片')
    ++one.level
  }
  one.newMessageName = filteredArrayAs12[i].messageUser
}

function getMessage() {
  get(`/cat/auth/message/${store.auth.user.id}`, (dataF) => {
    let filteredArrayAs12 = dataF.data.filter(obj => obj.type != 3);
    let filteredArrayAs3 = dataF.data.filter(obj => obj.type == 3);
    filteredArrayAs12.forEach(obj1 => {
      // 在第二个数组中查找相同字段的对象
      let matchingObj = filteredArrayAs3.find(obj2 => obj1.id === obj2.id);
      // 如果找到匹配的对象，进行修改
      if (matchingObj) {
        // 例如，将第一个数组的 name 字段修改为第二个数组的 age 字段
        obj1.message = `${obj1.username}撤回一条消息`
        obj1.type = 3
      }
    });
    for (let i = 0; i < filteredArrayAs12.length; i++) {
      if (!store.userList.userList.some(one => one.id == filteredArrayAs12[i].fromUserId)) {
        let find = store.friendList.friendList.find(one => one.id == filteredArrayAs12[i].fromUserId);
        if (find == null) {
          get(`/cat/user/${filteredArrayAs12[i].fromUserId}`, (data) => {
            let user
            if (filteredArrayAs12[i].fromUserId[0] == 'G') {
              user = {
                id: filteredArrayAs12[i].fromUserId,
                avatar: data.data.avatar,
                username: data.data.username,
                isGroup: true,
                level: 0,
                newMessage: '',
                newMessageName: ''
              }
            } else {
              user = {
                id: filteredArrayAs12[i].fromUserId,
                avatar: data.data.avatar,
                username: data.data.username,
                isGroup: false,
                level: 0,
                newMessage: ''
              }
            }
            store.userList.userList.push(user)
            offlineMessageProcessing(filteredArrayAs12, i);
          })
        } else {
          store.userList.userList.push(find)
          offlineMessageProcessing(filteredArrayAs12, i);
        }
      } else {
        offlineMessageProcessing(filteredArrayAs12, i);
      }
    }
    messageList.push.apply(messageList, filteredArrayAs12)
    store.MessageNum = filteredArrayAs12.length
  }, (data) => {

  })

}


</script>
<style scoped>


</style>